package com.hzlh.controller;

import com.alibaba.fastjson.JSON;
import com.hzlh.common.http.HttpService;
import com.hzlh.exception.GlobalException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author alexhu
 */
@RestController
public class ExampleController {
    @Autowired
    private HttpService httpService;

    @GetMapping("/echo/{name}")
    public String echoName(@PathVariable("name") String name) {
        return "Echo " + name;
    }

    @GetMapping("/hello")
    public String helloName() {
        return "Hello";
    }


    @GetMapping("/test")
    public Object test(String q) throws Exception{
        String tokenUrl = "http://183.129.253.102:21011/api/token/getToken?authorizationCode=82313887969942cead3ad51015d956eb";
        Map<String,String> header = new HashMap<>();
        header.put("Content-Type","application/json");
        String tokenResult = httpService.doGet(tokenUrl,null,header);
        if(!StringUtils.isEmpty(tokenResult)){
           Map tokenPo = JSON.parseObject(tokenResult,Map.class);
           if(!StringUtils.isEmpty(tokenPo.get("code")) && "200".equals(tokenPo.get("code").toString())){
               //cmp_token
                Map data =(Map) tokenPo.get("data");
                if(!StringUtils.isEmpty(data.get("cmp_token"))){
                    String token = data.get("cmp_token").toString();
                    String url = "http://183.129.253.102:21011/services/h2eoqc/dsquery";
                    Map<String,Object> map = new HashMap<>();
                    map.put("scjgj_qyjbxx_gsqy",q);
                    Map<String,String> headMap = new HashMap<>();
                    headMap.put("cmp_token",token);
                    headMap.put("Content-Type","application/json");
                    String result = httpService.doGet(url,map,headMap);
                    if(!StringUtils.isEmpty(result)){
                        Map<String,Object> resultMap=JSON.parseObject(result,Map.class);
                        if(resultMap.get("code").equals(200)){
                          List<Map<String,Object>> dataList =  ( List<Map<String,Object>>)resultMap.get("data");
                            for (Map<String, Object> item : dataList) {
                              System.out.print(item.get("scjgj_qyjbxx_id"));
                            }
                        }
                    }
                    throw GlobalException.build("获取数据失败"+result);
                }
           }
        }
       return "success";
    }
}